/**
 * @author Nicolas Zimerman (zimerman@usi.ch)
 * @author Isabella Nake (isabella.nake@usi.ch)
 * @author Nicolas Lusa (lusan@usi.ch)
 * @author Nicolas Latorre (nicolas.latorre@usi.ch)
 */
package ch.usi.inf.pf2.gui.action;

import java.util.ArrayList;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JLabel;

import ch.usi.inf.pf2.circuit.Input;
import ch.usi.inf.pf2.gui.CircuitFrame;
import ch.usi.inf.pf2.gui.Model;
import ch.usi.inf.pf2.time.Schedule;

public class StepRunAction extends AbstractAction{
	
	private static final long serialVersionUID = 5059530177195517424L;
	private final Model model;
	 private final CircuitFrame circuitFrame;

	    public StepRunAction(final CircuitFrame circuitFrame, final Model model) {
	        this.model = model;
	        this.circuitFrame = circuitFrame;
	        putValue(NAME, "Step Run");
	        final ImageIcon icon = new ImageIcon(getClass().getResource("../icons/steprun.png"));
	        putValue(SMALL_ICON, icon);
	        putValue(SHORT_DESCRIPTION, "Execute one step of the circuit.");
	    }

		@Override
		public void actionPerformed(ActionEvent arg0) {
			model.clearSelection();
			
			Schedule.stepRun();
			model.shapeChanged();
			
			ArrayList<Input> inputs = model.getInputs();
			circuitFrame.getEditor().removeAll();
			
			for(Input input : inputs) {
				if(input.getWaveform() != "") {
					System.out.println(Schedule.getStep()-1);
					if((Schedule.getStep() != 0) && (Schedule.getStep() <= input.getWaveform().length())) {
						char currentValue = input.getWaveform().charAt(Schedule.getStep()-1);
						circuitFrame.setEditor(new JLabel("<html><font>" +input.getName() + ": " +"</font><font>"+input.getWaveform().substring(0, Schedule.getStep()-1)
								+"</font><span style=\"BACKGROUND-COLOR: #32CD32\">" + currentValue + "</span><font>"+input.getWaveform().substring(Schedule.getStep())
								+"</font></html>"));
					}
					else {
						System.out.println("ELSE");
						char currentValue2 = input.getWaveform().charAt(input.getWaveform().length()-1); //this gives the last digit of waveform
						circuitFrame.setEditor(new JLabel("<html><font>" +input.getName() + ": " +"</font><font>"+input.getWaveform().substring(0, input.getWaveform().length() -1)
								+"</font><span style=\"BACKGROUND-COLOR: #32CD32\">" + currentValue2 + "</span></html>"));
					}
				}
			}
			circuitFrame.getEditor().revalidate();
		}


}
